package com.ants.cms.controller.ajax;

import com.alibaba.fastjson.JSON;
import com.ants.cms.common.utils.ResponseUtil;
import com.ants.cms.common.utils.SpringValidators;
import com.ants.cms.entity.News;
import com.ants.cms.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/9.
 */
@RestController
@RequestMapping("/test")
public class AuthorController {

    @Autowired
    private NewsService newsService;

    /**
     * 查询列表分页
     * @param pageCurrent 当前页数
     * @param pageSize 每页大小
     * @param filter 过滤字段 集合
     * @return
     */
    @RequestMapping(value = "/getNewsList", method = RequestMethod.GET)
    public Object getNewsList(@RequestParam Integer pageCurrent
            , @RequestParam Integer pageSize
            , String filter){
        Map conditions = null;
        if("".equals(filter))
            conditions = JSON.parseObject(filter, Map.class);
        return ResponseUtil.jsonSuccess(newsService.queryPage(pageCurrent, pageSize, conditions));
    }


    /**
     * 新增一条数据
     * @param news 实体
     * @param result 校验
     * @return
     */
    @RequestMapping(value = "/saveNews", method = RequestMethod.POST)
    public Object saveNews(News news, BindingResult result) {
        String errMsg = SpringValidators.validate(result);
        if (errMsg!=null) return ResponseUtil.jsonFail(errMsg);
        return ResponseUtil.jsonSuccess(newsService.insertSelective(news));
    }


    /**
     * 根据主键ID删除数据
     * @param ids 主键ID数组
     * @return
     */
    @RequestMapping(value = "/deleteNews", method = RequestMethod.POST)
    public Object deleteNews(@RequestParam("ids[]") List<Serializable> ids) {
        return ResponseUtil.jsonSuccess(newsService.deleteByIds(ids));
    }

    /**
     * 修改提交的实体数据
     * @param news 实体
     * @param result 校验
     * @return
     */
    @RequestMapping(value = "/modifyNews", method = RequestMethod.POST)
    public Object modifyNews(News news, BindingResult result) {
        String errMsg = SpringValidators.validate(result);
        if (errMsg!=null) return ResponseUtil.jsonFail(errMsg);
        return ResponseUtil.jsonSuccess(newsService.updateSelective(news));
    }

    /**
     * 根据主键ID查询单条数据
     * @param id 主键ID
     * @return
     */
    @RequestMapping(value = "/getNews", method = RequestMethod.GET)
    public Object getNews(@RequestParam Integer id) {
        return ResponseUtil.jsonSuccess(newsService.queryById(id));
    }
    
}
